package com.zhijian.medical.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.zhijian.medical.config.Constants;
import com.zhijian.medical.dao.local.DeviceCooperativeInstitutionMapper;
import com.zhijian.medical.entity.po.DeviceCooperativeInstitution;
import com.zhijian.medical.entity.po.Person;
import com.zhijian.medical.entity.po.PersonGroup;
import com.zhijian.medical.entity.po.PersonRole;
import com.zhijian.medical.entity.vo.request.DeviceCooperativeInstitutionSearchVo;
import com.zhijian.medical.entity.vo.request.PersonSearchVo;
import com.zhijian.medical.entity.vo.response.DeviceCooperativeInstitutionVo;
import com.zhijian.medical.entity.vo.response.OfficeGroupVo;
import com.zhijian.medical.entity.vo.response.RoleVo;
import com.zhijian.medical.enums.CooperativeInstitutionTypeEnum;
import com.zhijian.medical.enums.ResponseCodeEnum;
import com.zhijian.medical.exception.BusinessException;
import com.zhijian.medical.service.*;
import com.zhijian.medical.util.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 合作机构业务处理层
 *
 * @author HCG
 * @date 2022-01-01 15:39:16
 * @version: 1.0
 */
@Slf4j
@Service
public class DeviceCooperativeInstitutionServiceImpl implements DeviceCooperativeInstitutionService {

    @Autowired
    private DeviceCooperativeInstitutionMapper mapper;

    @Autowired
    private PersonService personService;

    @Autowired
    private OfficeGroupService officeGroupService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private PersonRoleService personRoleService;

    @Autowired
    private PersonGroupService personGroupService;

    @Override
    public DeviceCooperativeInstitution selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public DeviceCooperativeInstitutionVo selectVoById(Long id) {
        return mapper.selectVoById(id);
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public Long insert(DeviceCooperativeInstitution deviceCooperativeInstitution) {
        Date now = new Date();
        deviceCooperativeInstitution.setCreateTime(now);
        deviceCooperativeInstitution.setUpdateTime(now);
        return mapper.insert(deviceCooperativeInstitution) == 1 ? deviceCooperativeInstitution.getId() : 0L;
    }

    @Transactional(rollbackFor = Exception.class, value = "localTransactionManager")
    @Override
    public Long insertAll(DeviceCooperativeInstitution deviceCooperativeInstitution) {
        Long deviceCooperativeInstitutionId = this.insert(deviceCooperativeInstitution);
        if (deviceCooperativeInstitution.getType() != CooperativeInstitutionTypeEnum.SJ_CJ.getCode().byteValue()) {
            //下面的逻辑只跟试剂厂家有关
            return deviceCooperativeInstitutionId;
        }
        OfficeGroupVo officeGroupVo = officeGroupService.selectVoByName(Constants.GYS);
        if (Objects.isNull(officeGroupVo)) {
            throw new BusinessException(ResponseCodeEnum.FAILURE.code, "部门无供应商，请先在部门机构添加'供应商'");
        }
        //生成新的随机4位数的员工编号，要不重复
        String jobNumber;
        do {
            jobNumber = RandomUtil.randomNumbers(4);
        } while (personService.count(PersonSearchVo.builder()
                .jobNumber(jobNumber)
                .build()) > 0);

        //插入一条人员信息数据
        Long personId = personService.insert(Person.builder()
                .name(deviceCooperativeInstitution.getName())
                .phone(deviceCooperativeInstitution.getPhone())
                .jobNumber(jobNumber)
                .cooperativeInstitutionId(deviceCooperativeInstitutionId)
                .build());
        //找到试剂供应商角色
        RoleVo sjRoleVo = roleService.selectVoByName(Constants.SJ_GYS);
        if (Objects.isNull(sjRoleVo)) {
            throw new BusinessException(ResponseCodeEnum.FAILURE.code, "角色无试剂供应商，请先在角色添加'试剂供应商'");
        }
        //插入角色-人员关系表
        personRoleService.insert(PersonRole.builder()
                .personId(personId)
                .roleId(sjRoleVo.getId())
                .build());
        //插入人员-部门关系表
        personGroupService.insert(PersonGroup.builder()
                .personId(personId)
                .groupId(officeGroupVo.getId())
                .build());
        return deviceCooperativeInstitutionId;
    }

    @Override
    public boolean update(DeviceCooperativeInstitution deviceCooperativeInstitution) {
        Date now = new Date();
        deviceCooperativeInstitution.setUpdateTime(now);
        return mapper.updateByPrimaryKey(deviceCooperativeInstitution) != 0;
    }

    @Override
    public Integer count(DeviceCooperativeInstitutionSearchVo deviceCooperativeInstitutionSearchVo) {
        return mapper.count(deviceCooperativeInstitutionSearchVo);
    }

    @Override
    public List<DeviceCooperativeInstitutionVo> selectList(DeviceCooperativeInstitutionSearchVo deviceCooperativeInstitutionSearchVo) {
        return mapper.selectList(deviceCooperativeInstitutionSearchVo);
    }

    @Override
    public Page<DeviceCooperativeInstitutionVo> selectPage(DeviceCooperativeInstitutionSearchVo deviceCooperativeInstitutionSearchVo) {
        //先直接查总数
        int count = count(deviceCooperativeInstitutionSearchVo);
        //分页
        Page<DeviceCooperativeInstitutionVo> page = new Page<>(true, count, deviceCooperativeInstitutionSearchVo.getPageNum(), deviceCooperativeInstitutionSearchVo.getPageSize());
        deviceCooperativeInstitutionSearchVo.setStartIndex(page.getStartIndex());
        page.setPage(true);
        page.setTotalCount(count);
        List<DeviceCooperativeInstitutionVo> responseVos = this.selectList(deviceCooperativeInstitutionSearchVo);
        page.setData(responseVos);
        return page;
    }

}